package br.com.puertorico.mecanismos.ui.converters;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.w3c.tidy.Tidy;

/**
 * Respons&aacute;vel pela convers&atilde;o de um texto em html para xhtml.
 *
 * @author <a href="mailto:daniel.camargo@ufms.br">Daniel Camargo</a>
 * @version $id$
 */
public class XHTMLConverter implements Converter {

	/**
	 * {@inheritDoc}
	 */
	public Object getAsObject(FacesContext ctx, UIComponent ui, String value) {
		if (value == null || value.trim().length() == 0) {
			return null;
		}
		value = html2Xhtml(value);
		return value;
	}

	/**
	 * {@inheritDoc}
	 */
	public String getAsString(FacesContext ctx, UIComponent ui, Object value) {
		if (value == null) {
			return null;
		}
		return value.toString();
	}

	public static String html2Xhtml(String html) {
		if (html == null || html.trim().length() == 0) {
			return null;
		}
		InputStream in = new ByteArrayInputStream(html.getBytes());
		ByteArrayOutputStream out;
		Tidy tidy = new Tidy();
		tidy.setPrintBodyOnly(true);
		tidy.setQuiet(true);
		tidy.setShowWarnings(false);
		tidy.setXmlOut(true);
		tidy.setRawOut(true);
		tidy.setInputEncoding("UTF-8");
		tidy.setOutputEncoding("UTF-8");

		try {
			// Create input and output streams
			out = new ByteArrayOutputStream();
			// Convert files
			tidy.parse(in, out);
			byte[] bytes = out.toByteArray();
			String text = new String(bytes);
			html = text;
			// Clean up
			in.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return html;
	}
}